package com.cmcc.aregister.ui.activity;

import java.lang.reflect.Method;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.KeyboardView;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.cmcc.aregister.Controller;
import com.cmcc.aregister.KeyboardUtil;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.sdk.CmccDataStatistics;
import com.oauth.utils.InstalltionIdFactory;
import com.oauth.utils.LoginEncryptUtils;

public class UserLoginActivity extends LoginParentActivity
{
    private final String TAG = "UserLoginActivity";
    private Button registBtn, loginBtn, getPwdBtn, getVaildCodeBtn;
    private EditText mobileET, servicemobileET, pwdServiceET, pwdRandomET,
        checkCodeET;
    private String pwd = null;
    private String result;
    private DatabaseAdapter mDatabaseAdapter;
    private String url = "";
    // private TextView pwdTxt;
    private boolean isLoginClick = false;
    private boolean loadingInfo = false;
    private boolean isGetVaild = false;// 获取图片验证码标识
    private boolean isCheckVaild = false;// 验证图片验证码标识
    private LinearLayout loginParentLayout, checkCodeView;
    private RelativeLayout serviceLogin, smsLogin;
    private TextView serviceBtn, autoBtn;
    private LinearLayout serviceView;
    private RelativeLayout serviceLoginView, autoLoginView, checkCodeInputView;
    private CheckBox rmbPwdCheck, autoLoginCheck;
    int loginType = 2;// 默认是动态密码登陆
    private boolean is_auto_login = false;
    String[] responseArray = null;

    private String resultMsg;
    private String info_name, info_birth, info_card, info_social_card;
    private int info_sex;
    private boolean getInfo = false;

    private String validurl = "";
    private int vaildStatus;
    private Intent intent;
    private Activity act;
    private InputMethodManager imm;

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    /**
     * 进入首页
     */
    public void startIndexActivity()
    {
        Intent intent = new Intent(this, NewIndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        // pwdServiceET.setText("");
        // pwdRandomET.setText("");
        if (ConfigUtilHelper.has_regist)
        {
            ConfigUtilHelper.has_regist = false;
            mobileET.setText(ConfigUtilHelper.getMobileNum(this));
            pwdServiceET.setText("");
            pwdRandomET.setText("");
        }
        mobileET.requestFocus();
        /*
         * if(is_auto_login){ String mobile = ConfigUtilHelper.getMobile(this);
         * pwd = pwdServiceET.getText().toString(); url =
         * ConfigUtilHelper.loginUrl + "?&id=" + ConfigUtilHelper.loginId +
         * "&auth=" + ConfigUtilHelper.loginAuth + "&mobile=" + mobile +
         * "&password=" + pwd + "&login_type=" + loginType; isLoginClick = true;
         * showProgressDlg(getString(R.string.notice),
         * getString(R.string.logining)); }
         */
    }

    @Override
    protected void onStart()
    {
        // TODO Auto-generated method stub
        super.onStart();
        // loginParentLayout.setVisibility(View.VISIBLE);
        // Animation animation = AnimationUtils.loadAnimation(this,
        // R.anim.login_layout_anim);
        // loginParentLayout.startAnimation(animation);
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.p_user_login);
        act = this;
        intent = getIntent();
        if (!is_auto_login)
        {
            autoLoginView.setVisibility(View.VISIBLE);
            serviceLoginView.setVisibility(View.GONE);
            serviceView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setupData()
    {
        is_auto_login = getIntent()
            .getBooleanExtra(Arguments.AUTO_LOGIN, false);
    }

    @Override
    protected void setupView()
    {
        loginParentLayout = (LinearLayout) findViewById(R.id.login_parent_layout);
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.login_title);
        registBtn = (Button) findViewById(R.id.regist_btn);
        loginBtn = (Button) findViewById(R.id.login_btn);
        getPwdBtn = (Button) findViewById(R.id.get_password);
        getVaildCodeBtn = (Button) findViewById(R.id.get_vaild_code);
        mobileET = (EditText) findViewById(R.id.mobile);
        servicemobileET = (EditText) findViewById(R.id.service_mobile);
        pwdServiceET = (EditText) findViewById(R.id.pwd_service);
        pwdRandomET = (EditText) findViewById(R.id.pwd_random);
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16)
        {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        }
        else if (currentVersion >= 14)
        {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }
        if (methodName == null)
        {
            pwdServiceET.setInputType(InputType.TYPE_NULL);
        }
        else
        {
            getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try
            {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod(methodName,
                    boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(pwdServiceET, false);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        servicemobileET.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                new KeyboardUtil(act, context, pwdServiceET).hideKeyboard();
                return false;
            }
        });
        pwdServiceET.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                new KeyboardUtil(act, context, pwdServiceET).showKeyboard();
                return false;
            }
        });

        checkCodeET = (EditText) findViewById(R.id.check_code);
        // pwdTxt = (TextView) findViewById(R.id.pwd_txt);
        checkCodeView = (LinearLayout) findViewById(R.id.linear);
        checkCodeInputView = (RelativeLayout) findViewById(R.id.check_code_input_view);
        registBtn.setOnClickListener(onClickListener);
        loginBtn.setOnClickListener(onClickListener);
        getPwdBtn.setOnClickListener(onClickListener);
        getVaildCodeBtn.setOnClickListener(onClickListener);

        mDatabaseAdapter = new DatabaseAdapter(this);

        serviceBtn = (TextView) findViewById(R.id.service_pwd);
        serviceBtn.setOnClickListener(onClickListener);
        autoBtn = (TextView) findViewById(R.id.random_pwd);
        autoBtn.setOnClickListener(onClickListener);
        serviceLogin = (RelativeLayout) findViewById(R.id.service_mobile_input);
        smsLogin = (RelativeLayout) findViewById(R.id.mobile_input);
        serviceLoginView = (RelativeLayout) findViewById(R.id.service_input_view);
        autoLoginView = (RelativeLayout) findViewById(R.id.auto_input_view);
        serviceView = (LinearLayout) findViewById(R.id.service_view);
        rmbPwdCheck = (CheckBox) findViewById(R.id.rmb_pwd);
        rmbPwdCheck.setChecked(false);
        autoLoginCheck = (CheckBox) findViewById(R.id.auto_login_check);
        autoLoginCheck.setChecked(false);
        rmbPwdCheck.setOnCheckedChangeListener(onCheckedChangeListener);
        autoLoginCheck.setOnCheckedChangeListener(onCheckedChangeListener);

        initCheckBox();
    }

    OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked)
        {
            if (buttonView == rmbPwdCheck)
            {
                if (!rmbPwdCheck.isChecked())
                {
                    if (autoLoginCheck.isChecked())
                    {
                        autoLoginCheck.setChecked(false);
                    }
                }
            }
            if (buttonView == autoLoginCheck)
            {
                if (autoLoginCheck.isChecked())
                {
                    if (!rmbPwdCheck.isChecked())
                    {
                        rmbPwdCheck.setChecked(true);
                    }
                }
            }
        }
    };

    /**
     * 验证图片验证码
     */
    private void checkCode()
    {
        String code = checkCodeET.getText().toString();
        if ("".equals(code))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.code_null), getString(R.string.dialog_yes));
            return;
        }
        String mobile = mobileET.getText().toString().trim()
            .replaceAll("\\s*", "");
        if (mobile.length() == 11)
        {
            if (!ConfigUtilHelper.isMobileNum11(mobile))
            {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.mobile_err),
                    getString(R.string.dialog_yes));
                return;
            }
        }
        url = ConfigUtilHelper.checkVaildCode + "?&id="
            + ConfigUtilHelper.loginId + "&auth=" + ConfigUtilHelper.loginAuth
            + "&mobile=" + mobile + "&validcode=" + code + "&ostype=" + 4;// 4表示android平台
        isCheckVaild = true;
        showProgressDlg(getString(R.string.notice),
            getString(R.string.check_vaild_code));
    }

    private void checkLogin()
    {
        String mobile = "";
        String pwd = "";
        if (loginType == 1)
        {
            pwd = pwdServiceET.getText().toString();
            mobile = servicemobileET.getText().toString().trim()
                .replaceAll("\\s*", "");
        }
        else
        {
            mobile = mobileET.getText().toString().trim()
                .replaceAll("\\s*", "");
            pwd = pwdRandomET.getText().toString();
        }
        if (!ConfigUtilHelper.isNotEmpty(mobile))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_null), getString(R.string.dialog_yes));
        }
        else if (!ConfigUtilHelper.isMobileNum11(mobile))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_err), getString(R.string.dialog_yes));
        }
        else if (!ConfigUtilHelper.isNotEmpty(pwd))
        {
            if (serviceLoginView.getVisibility() == View.VISIBLE)
            {// 服务密码为空
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.login_input_service_pwd),
                    getString(R.string.dialog_yes));
            }
            else
            {// 动态密码为空
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.login_input_auto_pwd),
                    getString(R.string.dialog_yes));
            }
        }
        else if (pwd.length() < 6)
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.login_input_pwd_too_short),
                getString(R.string.dialog_yes));
        }
        else
        {
            /*
             * String t = pwdTxt.getText().toString(); if
             * (t.equals(getString(R.string.pwd))) { loginType = 2; }
             */
            if (serviceView.getVisibility() == View.VISIBLE)
            {// 如果是记住密码和自动登陆看得到就说明是服务密码在登陆
                serviceLogin.setVisibility(View.VISIBLE);
                smsLogin.setVisibility(View.GONE);
                checkCodeInputView.setVisibility(View.GONE);
                loginType = 1;
            }
            else
            {
                loginType = 2;
            }
            // 组装登陆请求地址。
            // 如果为服务密码登陆，对密码进行加密。
            if (loginType == 1)
            {
                try
                {
                    pwd = LoginEncryptUtils.encodeString("szicity20131119",
                        pwd, true);
                    // pwd = URLEncoder.encode(pwd, "UTF-8");
                }
                catch (Exception e)
                {
                    Log.i(TAG, "对密码加密出现异常");
                }
            }
            url = ConfigUtilHelper.loginUrl + "?&id="
                + ConfigUtilHelper.loginId + "&auth="
                + ConfigUtilHelper.loginAuth + "&mobile=" + mobile
                + "&password=" + pwd + "&login_type=" + loginType + "&ostype="
                + 2;
            isLoginClick = true;
            showProgressDlg(getString(R.string.notice),
                getString(R.string.logining));
        }
    }

    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            switch (v.getId())
            {
            case R.id.service_pwd:
                checkCodeInputView.setVisibility(View.GONE);
                String mobile01 = servicemobileET.getText().toString().trim()
                    .replaceAll("\\s*", "");
                if (mobile01.length() == 11)
                {
                    if (!ConfigUtilHelper.isMobileNum(mobile01))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.mobile_err),
                            getString(R.string.dialog_yes));
                    }
                }
                serviceBtn.setTextColor(getResources().getColor(
                    R.color.sky_blue));
                autoBtn.setTextColor(getResources().getColor(R.color.gray));
                serviceLoginView.setVisibility(View.VISIBLE);
                autoLoginView.setVisibility(View.GONE);
                serviceView.setVisibility(View.VISIBLE);
                serviceLogin.setVisibility(View.VISIBLE);
                smsLogin.setVisibility(View.GONE);
                loginType = 1;
                break;
            case R.id.get_vaild_code:
                getVaildCode();
                break;
            case R.id.random_pwd:
                checkCodeInputView.setVisibility(View.VISIBLE);
                String mobile02 = mobileET.getText().toString().trim()
                    .replaceAll("\\s*", "");
                if (mobile02.length() == 11)
                {
                    if (!ConfigUtilHelper.isMobileNum11(mobile02))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.mobile_err),
                            getString(R.string.dialog_yes));
                    }
                }
                autoBtn.setTextColor(getResources().getColor(R.color.sky_blue));
                serviceBtn.setTextColor(getResources().getColor(R.color.gray));
                serviceView.setVisibility(View.GONE);
                serviceLoginView.setVisibility(View.GONE);
                autoLoginView.setVisibility(View.VISIBLE);
                serviceLogin.setVisibility(View.GONE);
                smsLogin.setVisibility(View.VISIBLE);
                mobileET.setHint("手机号码(支持移动、电信、联通)");
                loginType = 2;
                break;
            case R.id.regist_btn:
                gotoRegist();
                break;
            case R.id.login_btn:
                checkLogin();
                break;
            case R.id.get_password:
                checkCode();
                break;
            case R.id.txt01:
                joinLink(ConfigUtilHelper.url01);
                break;
            case R.id.txt02:
                joinLink(ConfigUtilHelper.url02);
                break;
            case R.id.txt03:
                joinLink(ConfigUtilHelper.url03);
                break;
            default:
                break;
            }
        }

    };

    /**
     * 获取图片验证码
     */
    private void getVaildCode()
    {
        String mobile = mobileET.getText().toString().trim()
            .replaceAll("\\s*", "");
        if (mobile.equals(""))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_null), getString(R.string.dialog_yes));
            return;
        }
        else if (mobile.length() != 11 || !mobile.startsWith("1"))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_err), getString(R.string.dialog_yes));
            return;
        }
        else if (!ConfigUtilHelper.isMobileNum11(mobile))
        {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.mobile_err), getString(R.string.dialog_yes));
            return;
        }
        url = ConfigUtilHelper.getVaildCode + "?&id="
            + ConfigUtilHelper.loginId + "&auth=" + ConfigUtilHelper.loginAuth
            + "&mobile=" + mobile + "&ostype=" + 4;// 4 表示android平台
        isGetVaild = true;
        showProgressDlg(getString(R.string.notice),
            getString(R.string.get_vaild_code));
    }

    /**
     * 去注册
     */
    private void gotoRegist()
    {
        Intent intent = new Intent(UserLoginActivity.this,
            UserRegisterActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void showProgressDlg(String title, String msg)
    {
        final ProgressDialog loadingDlg = new ProgressDialog(this);
        loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDlg.setTitle(title);
        loadingDlg.setMessage(msg);
        loadingDlg.setIcon(android.R.drawable.ic_dialog_info);
        loadingDlg.setCancelable(true);
        loadingDlg.show();
        new Thread() {
            public void run()
            {
                try
                {
                    progressRun();
                }
                catch (Exception e)
                {
                    loadingDlg.dismiss();
                }
                loadingDlg.dismiss();
            }
        }.start();
        loadingDlg
            .setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog)
                {
                    // TODO Auto-generated method stub
                    doWork();
                }

            });
    }

    private void progressRun()
    {
        result = ConfigUtilHelper.request(url);
        if (ConfigUtilHelper.debug)
        {
            Log.i(TAG, "------->" + result);
        }
        if (result == null || result.equals(""))
        {
            return;
        }
        if (result == null)
        {
            getInfo = false;
            return;
        }
        // 获取图片验证码
        if (isGetVaild)
        {
            try
            {
                JSONObject joson = new JSONObject(result);
                vaildStatus = joson.getInt("status");
                validurl = joson.getString("validurl");
            }
            catch (Exception e)
            {

            }
        }
        // 验证图片验证码
        if (isCheckVaild)
        {
            try
            {
                JSONObject joson = new JSONObject(result);
                vaildStatus = joson.getInt("status");
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        if (loadingInfo)
        {
            try
            {
                JSONObject joson = new JSONObject(result);
                int status = joson.getInt("status");
                if (status == 0)
                {
                    getInfo = true;
                }
                else
                {
                    getInfo = false;
                }
                resultMsg = joson.getString("message");
                if (ConfigUtilHelper.debug)
                {
                    Log.i(TAG, "--resultMsg-->" + resultMsg);
                }
                if (getInfo)
                {
                    JSONObject josonData = new JSONObject(
                        joson.getString("data"));
                    info_name = josonData.getString("name");
                    info_birth = josonData.getString("birth");
                    info_sex = 0;
                    try
                    {
                        String info_sex_str = josonData.getString("sex");
                        if (info_sex_str.equals("null"))
                        {
                            info_sex = 0;
                        }
                        else
                        {
                            info_sex = Integer.parseInt(info_sex_str);
                        }
                    }
                    catch (Exception e)
                    {}
                    info_card = josonData.getString("card");
                    info_social_card = josonData.getString("social_card");
                    if (info_name.equals("null"))
                    {
                        info_name = "";
                    }
                    if (info_birth.equals("null"))
                    {
                        info_birth = "";
                    }
                    if (info_social_card.equals("null"))
                    {
                        info_social_card = "";
                    }
                    if (info_card.equals("null"))
                    {
                        info_card = "";
                    }
                    if (ConfigUtilHelper.debug)
                    {
                        Log.i(TAG, "--result-->" + " info_name:" + info_name
                            + " info_birth:" + info_birth + " info_sex"
                            + info_sex + " info_card" + info_card
                            + " info_social_card" + info_social_card);
                    }
                }

            }
            catch (JSONException e)
            {

            }
            return;
        }

    }

    private void checkInternet()
    {
        showSingleAlertDlg(getString(R.string.notice),
            getString(R.string.dialog_check_internet),
            getString(R.string.dialog_close));
    }

    String uid, token;

    private void doWork()
    {
        if (isGetVaild)
        {
            isGetVaild = false;
            switch (vaildStatus)
            {
            case 0:
                Drawable drawable = loadImageFromNetwork(validurl);
                checkCodeView.setBackgroundDrawable(drawable);
                break;
            case 401:
                showSingleAlertDlg(getString(R.string.notice), "参数不齐！",
                    getString(R.string.dialog_close));
                break;
            case 406:
                showSingleAlertDlg(getString(R.string.notice), "auth证认错误！",
                    getString(R.string.dialog_close));
                break;
            case 201:
                showSingleAlertDlg(getString(R.string.notice), "图形验证码生成失败！",
                    getString(R.string.dialog_close));
                break;
            }
            return;
        }
        if (isCheckVaild)
        {
            isCheckVaild = false;
            switch (vaildStatus)
            {
            case 0:
                getVaildCode();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.pwd_send),
                    getString(R.string.dialog_yes));
                break;
            case 401:
                showSingleAlertDlg(getString(R.string.notice), "参数不齐！",
                    getString(R.string.dialog_close));
                break;
            case 406:
                showSingleAlertDlg(getString(R.string.notice), "auth证认错误！",
                    getString(R.string.dialog_close));
                break;
            case 201:
                showSingleAlertDlg(getString(R.string.notice), "图形验证码输入错误！",
                    getString(R.string.dialog_close));
                break;
            }
            return;
        }

        if (loadingInfo)
        {
            loadingInfo = false;
            if (result == null || result.equals(""))
            {
                Toast.makeText(UserLoginActivity.this,
                    R.string.load_user_info_err, Toast.LENGTH_SHORT).show();
                return;
            }
            long dateMillis = System.currentTimeMillis();
            String loginDate = Long.toString(dateMillis);

            String mobile = "";

            if (loginType == 1)
            {
                mobile = servicemobileET.getText().toString().trim()
                    .replaceAll("\\s*", "");
            }
            else
            {
                mobile = mobileET.getText().toString().trim()
                    .replaceAll("\\s*", "");
            }
            if (!getInfo)
            {
                info_birth = "";
                info_name = "";
                info_sex = 0;
                info_card = "";
                info_social_card = "";
            }
            insertUserInfo(info_name, mobile, info_birth, info_sex, info_card,
                info_social_card, loginDate);

            reqClientInfo(mobile);

            CmccDataStatistics.Comm_Login(this, mobile);
            // CmccDataStatistics.onEvent(this, 0, mobile);
            // CmccDataStatistics.onEvent(this, 0,
            // "yiliaoyuyueguahaoandroid1645");
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (ConfigUtilHelper.isFromMain)
            {
                Message msg = new Message();
                msg.setTarget(ConfigUtilHelper.mHandler);
                msg.sendToTarget();
                ConfigUtilHelper.isFromMain = false;
            }

            String backUrl = intent.getStringExtra("callbackUrl");
            boolean fromAdPage = intent.getBooleanExtra("fromAdPage", false);
            if (backUrl != null)
            {
                Intent intent = new Intent(UserLoginActivity.this,
                    YdzqWebsiteLoading.class);
                intent.putExtra("callbackUrl", backUrl);
                intent.putExtra("fromAdPage", fromAdPage);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
            finish();
            return;
        }
        if (result == null)
        {
            if (!connectedNetwork())
            {
                checkInternet();
            }
            else
            {
                if (isLoginClick)
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.login_failed),
                        getString(R.string.dialog_yes));
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.get_pwd_err),
                        getString(R.string.dialog_yes));
                }
            }
            return;
        }
        else
        {
            if (!result.contains("|"))
            {
                if (isLoginClick)
                {// 登陆返回结果
                    if (result.substring(0, 3).equals("404"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_404),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("100"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_100),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("102"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_102),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("103"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_103),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("104"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_104),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("105"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_105),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("107"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_107),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("108"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_failed_108),
                            getString(R.string.dialog_yes));
                        // getPwdBtn.setEnabled(true);
                        return;
                    }
                }
                else
                {// 获取验证码的时候返回的结果判断
                    getVaildCode();
                    if (result.substring(0, 3).equals("201"))
                    {
                        // getPwdBtn.setText(getString(R.string.check_sms));
                        // pwdTxt.setText(getString(R.string.pwd));
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.get_pwd_over_three),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("405"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.get_pwd_err_405),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("407"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.login_warning_03),
                            getString(R.string.dialog_yes));
                        return;
                    }
                    else if (result.substring(0, 3).equals("402")
                        || result.substring(0, 3).equals("406"))
                    {
                        showSingleAlertDlg(getString(R.string.notice),
                            getString(R.string.get_pwd_err),
                            getString(R.string.dialog_yes));
                        return;
                    }
                }
            }
        }
        String[] t = result.split("\\|");
        if (t.length == 2)
        {
            pwd = t[1];
        }
        if (pwd != null)
        {
            if (pwd.length() == 6)
            {// 获取验证码成功
             // showSingleAlertDlg(getString(R.string.notice),
             // getString(R.string.pwd_send),
             // getString(R.string.dialog_yes));
             // getVaildCode();
            }
            else
            {// 登入成功->获取登陆者信息并填入数据库
                String[] uid_tokens = result.split("\\|");
                if (uid_tokens.length == 2)
                {
                    uid = uid_tokens[0];// 获取的uid
                    token = uid_tokens[1];// 获取的token
                    ConfigUtilHelper.saveUid(this, uid);
                    ConfigUtilHelper.saveToken(this, token);
                }
                String mobile = "";
                if (loginType == 1)
                {
                    mobile = servicemobileET.getText().toString().trim()
                        .replaceAll("\\s*", "");
                    String pwd = pwdServiceET.getText().toString();
                    if (rmbPwdCheck.isChecked() || autoLoginCheck.isChecked())
                    {
                        ConfigUtilHelper.saveMobileSharedPreferences(this,
                            mobile);
                        ConfigUtilHelper.savePwdSharedPreferences(this, pwd);
                    }
                    if (rmbPwdCheck.isChecked())
                    {
                        ConfigUtilHelper.saveRmbPwdFlag(this, true);
                    }
                    if (autoLoginCheck.isChecked())
                    {// 如果是自动登陆，那么存储手机号码和服务密码
                        ConfigUtilHelper.saveAutoLogin(this, true);
                    }
                    boolean s = ConfigUtilHelper
                        .getAutoLogin(UserLoginActivity.this);
                }
                else
                {
                    mobile = mobileET.getText().toString().trim()
                        .replaceAll("\\s*", "");
                }

                loadingInfo = true;
                url = ConfigUtilHelper.getInfoUrl + "&client_auth="
                    + GlobalSetting.CLIENT_AUTH + "&token="
                    + GlobalSetting.TOKEN + "&type=" + GlobalSetting.TYPE
                    + "&mobile=" + mobile;
                showProgressDlg(getString(R.string.notice),
                    getString(R.string.logining_info));

            }
        }
        else
        {
            if (isLoginClick)
            {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.login_err),
                    getString(R.string.dialog_yes));
            }
            else
            {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.get_pwd_err),
                    getString(R.string.dialog_yes));
            }
        }
    }

    /**
     * 存储用户信息
     * @param username
     * @param mobile
     * @param birth
     * @param sex
     * @param card
     * @param SCard
     * @param loginDate
     */
    private void insertUserInfo(String username, String mobile, String birth,
        int sex, String card, String SCard, String loginDate)
    {
        mDatabaseAdapter.open_user();
        Cursor c = mDatabaseAdapter.fetchAllUserData();
        if (c != null)
        {
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "--user count----->" + c.getCount());
            }
            if (c.getCount() > 0)
            {
                mDatabaseAdapter.deleteAllUserData();
                mDatabaseAdapter.insertUserData(username, mobile, birth, sex,
                    card, SCard, loginDate);
            }
            else
            {
                mDatabaseAdapter.insertUserData(username, mobile, birth, sex,
                    card, SCard, loginDate);
            }
        }
        SharedPreferences mSharedPreferences = getSharedPreferences(
            ConfigUtilHelper.INFO_VISIBLE_PREFS, Context.MODE_PRIVATE);
        Editor edit = mSharedPreferences.edit();
        edit.putBoolean(ConfigUtilHelper.IS_LOGIN, true);
        edit.commit();

        Cursor c2 = mDatabaseAdapter.fetchAllUserData();
        if (c2 != null && c2.getCount() > 0)
        {
            c2.moveToFirst();
            if (ConfigUtilHelper.debug)
            {
                Log.i(TAG, "--user count---after-->" + c2.getCount());
            }
            /*
             * if (ConfigUtilHelper.debug) { Log.i(TAG, "--user count---data-->"
             * + c2.getInt(c2.getColumnIndex("_id")) + "  " +
             * c2.getString(c2.getColumnIndex("username")) + "  " +
             * c2.getString(c2.getColumnIndex("mobile")) + "  " +
             * c2.getString(c2.getColumnIndex("birth")) + "  " +
             * c2.getInt(c2.getColumnIndex("sex")) + "  " +
             * c2.getString(c2.getColumnIndex("card")) + "  " +
             * c2.getString(c2.getColumnIndex("social_card")) + "  " +
             * c2.getString(c2.getColumnIndex("login_date"))); }
             */
        }
        c.close();
        c2.close();
        mDatabaseAdapter.close_user();
    }

    TextView txt01, txt02, txt03;

    public void showSingleAlertDlg02(String title, String posTitle)
    {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.notice_layout, null);
        txt01 = (TextView) view.findViewById(R.id.txt01);
        txt01.setOnClickListener(onClickListener);
        txt02 = (TextView) view.findViewById(R.id.txt02);
        txt02.setOnClickListener(onClickListener);
        txt03 = (TextView) view.findViewById(R.id.txt03);
        txt03.setOnClickListener(onClickListener);
        new AlertDialog.Builder(this).setTitle(title).setView(view)
            .setIcon(android.R.drawable.ic_dialog_info).setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    mobileET.setText("");
                    servicemobileET.setText("");
                }
            }).create().show();
    }

    private void joinLink(String url)
    {
        Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

        it.setClassName("com.android.browser",
            "com.android.browser.BrowserActivity");

        startActivity(it);

    }

    private void initCheckBox()
    {
        mobileET.setText(ConfigUtilHelper.getMobileNum(this));
        servicemobileET.setText(ConfigUtilHelper.getMobileNum(this));
        /*
         * if(ConfigUtilHelper.getRmbPwdFlag(this) ||
         * ConfigUtilHelper.getAutoLogin(this)){
         * pwdServiceET.setText(ConfigUtilHelper.getServicePwd(this)); }
         */
        pwdServiceET.setText(ConfigUtilHelper.getServicePwd(this));
        if (ConfigUtilHelper.getRmbPwdFlag(this))
        {
            // rmbPwdCheck.setChecked(true);
        }
        if (is_auto_login)
        {
            autoBtn.setTextColor(getResources().getColor(R.color.gray));
            serviceBtn.setTextColor(getResources().getColor(R.color.sky_blue));
            serviceLoginView.setVisibility(View.VISIBLE);
            autoLoginView.setVisibility(View.GONE);
            serviceView.setVisibility(View.VISIBLE);
            servicemobileET.setHint("手机号码(仅支持移动号码)");
            loginType = 1;
            // autoLoginCheck.setChecked(true);
            login();
        }
    }

    private void login()
    {
        checkLogin();
    }

    private HttpAsyncTask reqClientInfoTask;

    /**
     * 注册推送登陆用户信息。
     * @param phone
     */
    private void reqClientInfo(String phone)
    {
        JSONObject obj = new JSONObject();
        try
        {
            obj.put("request_type", Arguments.REQ_CLIENT_INFO_ACTION);
            obj.put("app_key", ConfigUtilHelper.getAppKey(context));
            String alias = InstalltionIdFactory.id(context).replaceAll("-", "");
            obj.put("alias", alias);
            obj.put("platform", "0");
            obj.put("phone", phone);
            obj.put("channel", ConfigUtilHelper.getChannel(context));
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        String params = obj.toString();
        reqClientInfoTask = new HttpAsyncTask(
            GlobalSetting.XML_GET_CILENT_INFO_TASK,
            Arguments.CLIENT_PUSH_SERVICE_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        Controller.getInstance().execute(reqClientInfoTask);
    }
}